<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>用户列表</el-breadcrumb-item> -->
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              type="primary"
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col> -->
        <el-col :span="4">
          <el-button type="primary" @click="deleteUsers"
            >删除指定用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="userlist"
        height="450"
        stripe
        border
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选栏 -->
        <!-- <el-table-column type="index"> </el-table-column> -->
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="userName" label="姓名"> </el-table-column>
        <!-- <el-table-column prop="zhuanye" label="专业"> </el-table-column> -->
        <el-table-column label="专业">{{ "软件工程" }} </el-table-column>
        <el-table-column prop="userIdentity" label="政治面貌">
          <template slot-scope="scope">
            <el-tag type="danger">
              {{ scope.row.userIdentity }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAdmin" label="管理员">
          <template slot-scope="scope">
            <el-switch
              active-color="#d43c33"
              v-model="scope.row.isAdmin"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.userId)"
              >删除</el-button
            >
            <!-- <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="changeRoleDialog(scope.row)"
            ></el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeAddForm"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editVisible"
      @close="closeEditForm"
    >
      <el-form
        :model="editForm"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="政治面貌">
          <!-- 政治面貌选择 -->
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //定义邮箱的正则表达式
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //定义手机号的正则表达式
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 15
      },
      // 用户列表
      userlist: [],
      // 用户修改信息列表
      userEditList: [],
      total: 0,
      dialogVisible: false,
      editVisible: false, //修改用户信息对话框显示与隐藏
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {},
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" }
          // { validator: checkMobile, trigger: "blur" }
        ]
      },
      changeForm: {},
      changeVisible: false,
      // 用户信息
      userinfo: {},
      selectRole: "",
      roleList: [],
      // 用户删除列表
      userDeleteIdList: [],
      // 政治面貌选择
      options: [
        {
          value: 1,
          label: "正式党员"
        },
        {
          value: 2,
          label: "预备党员"
        },
        {
          value: 3,
          label: "发展对象"
        },
        {
          value: 4,
          label: "积极分子"
        },
        {
          value: 5,
          label: "共青团员"
        },
        {
          value: 6,
          label: "群众"
        }
      ],
      // 当前选中
      value: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 多选勾选时将对应userId添加到删除序列
    handleSelectionChange(rows) {
      this.userDeleteIdList = [];
      rows.forEach(item => {
        this.userDeleteIdList.push(item.userId);
      });
      console.log(this.userDeleteIdList);
    },
    // 改变管理员状态
    async userStateChange(userinfo) {
      let changeForm = userinfo;
      if (changeForm.isAdmin == true) changeForm.isAdmin = 1;
      else changeForm.isAdmin = 0;
      if (changeForm.userIdentity === "正式党员") changeForm.userIdentity = 1;
      else if (changeForm.userIdentity === "预备党员")
        changeForm.userIdentity = 2;
      else if (changeForm.userIdentity === "发展对象")
        changeForm.userIdentity = 3;
      else if (changeForm.userIdentity === "积极分子")
        changeForm.userIdentity = 4;
      else if (changeForm.userIdentity === "共青团员")
        changeForm.userIdentity = 5;
      else if (changeForm.userIdentity === "群众") changeForm.userIdentity = 6;
      else changeForm.userIdentity = 1;
      // 改变状态
      console.log(changeForm);
      const { data: res } = await this.$http.post(
        "user/updateUser",
        changeForm
      );
      if (res.code !== 200) {
        this.$message.error("更新用户信息失败！");
      }
      this.$message.success("修改成功！");
      this.getUserList();
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 获取用户列表
    async getUserList() {
      let res = "";
      if (this.queryInfo.query) {
        const { data: res1 } = await this.$http.get(
          `/user/fuzzySearch/${this.queryInfo.query}/${this.queryInfo.pagenum}`
        );
        res = res1;
      } else {
        const { data: res1 } = await this.$http.get(
          "user/getAllUser/" + this.queryInfo.pagenum
        );
        res = res1;
      }
      if (res.code != 200) {
        return this.$message.error("获取用户列表失败！");
      }
      // 用户列表
      this.userlist = res.data.userList;
      // 总数
      this.total = res.data.total;
      this.userlist.forEach(item => {
        if (item.userIdentity === 0) item.userIdentity = "待填写";
        else if (item.userIdentity === 1) item.userIdentity = "正式党员";
        else if (item.userIdentity === 2) item.userIdentity = "预备党员";
        else if (item.userIdentity === 3) item.userIdentity = "发展对象";
        else if (item.userIdentity === 4) item.userIdentity = "积极分子";
        else if (item.userIdentity === 5) item.userIdentity = "共青团员";
        else if (item.userIdentity === 6) item.userIdentity = "群众";
        if (item.isAdmin === 0) item.isAdmin = false;
        else item.isAdmin = true;
      });
    },
    // 关闭对话框清空表单
    closeAddForm() {
      this.$refs.ruleForm.resetFields();
    },
    // 关闭编辑信息对话框
    closeEditForm() {
      this.$refs.editForm.resetFields();
      this.getUserList();
    },
    // 添加用户
    async addUser() {
      this.$refs.ruleForm.validate(async value => {
        if (!value) return;
        // const { data: res } = await this.$http.post("users", this.addForm);
        // console.log(res);
        // if (res.code !== 200) return this.$message.error("添加用户失败！");
        // this.$message.success("添加用户成功！");
        // this.dialogVisible = false;
        // this.getUserList();
      });
    },
    // 打开修改用户信息对话框
    async showEditDialog(userinfo) {
      this.editForm = userinfo;
      if (userinfo.userIdentity === "正式党员") this.value = 1;
      else if (userinfo.userIdentity === "预备党员") this.value = 2;
      else if (userinfo.userIdentity === "发展对象") this.value = 3;
      else if (userinfo.userIdentity === "积极分子") this.value = 4;
      else if (userinfo.userIdentity === "共青团员") this.value = 5;
      else if (userinfo.userIdentity === "群众") this.value = 6;
      else this.value = 1;
      this.editVisible = true;
    },
    // 修改用户信息
    async editUser() {
      this.$refs.editForm.validate(async value => {
        if (!value) return;
        if (this.editForm.isAdmin == false) this.editForm.isAdmin = 0;
        else this.editForm.isAdmin = 1;
        this.editForm.userIdentity = this.value;
        const { data: res } = await this.$http.post(
          "user/updateUser",
          this.editForm
        );
        if (res.code !== 200) {
          this.$message.error("更新用户信息失败！");
        }
        this.$message.success("更新用户信息成功！");
        this.getUserList();
        this.editVisible = false;
      });
    },
    // 删除单个用户
    async deleteUser(id) {
      const deleteResult = await this.$confirm("是否删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        // center: true
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.delete("user/deleteUser/" + id);
      if (res.code !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getUserList();
    },
    // 删除多个用户
    async deleteUsers() {
      const deleteResult = await this.$confirm("是否删除选定用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        // center: true
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.post(
        "user/deleteBatchUser",
        this.userDeleteIdList
      );
      if (res.code !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getUserList();
    }
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
</style>